<template>
  <div class="question-review-container">
    <div class="page-header">
      <h2>题目审核</h2>
      <div class="header-actions">
        <div class="filter-container">
          <el-input
            v-model="searchQuery"
            placeholder="搜索题目内容"
            class="filter-item"
            :prefix-icon="Search"
            @input="handleSearch"
            clearable
          />
          <el-select
            v-model="contestFilter"
            placeholder="选择竞赛"
            class="filter-item"
            @change="handleFilter"
            clearable
          >
            <el-option
              v-for="contest in contestOptions"
              :key="contest.id"
              :label="contest.title"
              :value="contest.id"
            />
          </el-select>
          <el-select
            v-model="typeFilter"
            placeholder="题目类型"
            class="filter-item"
            @change="handleFilter"
            clearable
          >
            <el-option
              v-for="type in questionTypes"
              :key="type.id"
              :label="type.typeName"
              :value="type.id"
            />
          </el-select>
          <el-select
            v-model="statusFilter"
            placeholder="状态筛选"
            class="filter-item"
            @change="handleFilter"
            clearable
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>
    </div>

    <el-card shadow="hover" class="list-card">
      <el-table
        v-loading="loading"
        :data="questionList"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="content" label="题目内容" min-width="300">
          <template #default="scope">
            <el-tooltip 
              effect="dark" 
              :content="scope.row.content" 
              placement="top" 
              :hide-after="0"
            >
              <div class="question-content">{{ formatContent(scope.row.content) }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="contestTitle" label="所属竞赛" width="150" align="center">
          <template #default="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.contestTitle"
              placement="top"
              :hide-after="0"
              v-if="scope.row.contestTitle && scope.row.contestTitle.length > 12"
            >
              <span>{{ formatText(scope.row.contestTitle, 12) }}</span>
            </el-tooltip>
            <span v-else>{{ scope.row.contestTitle || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="题目类型" width="100" align="center">
          <template #default="scope">
            <el-tag 
              :type="getTypeTagType(scope.row.typeId)" 
              effect="plain"
            >
              {{ getQuestionTypeName(scope.row.typeId) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="80" align="center">
          <template #default="scope">
            <el-tag 
              :type="getDifficultyTagType(scope.row.difficulty)" 
              effect="light"
            >
              {{ getDifficultyText(scope.row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分值" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag 
              :type="getStatusTagType(scope.row.status)" 
              effect="light"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="viewQuestion(scope.row.id)"
            >
              查看
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="success"
              link
              @click="approveQuestion(scope.row.id)"
            >
              通过
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="danger"
              link
              @click="rejectQuestion(scope.row.id)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 题目详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="题目详情"
      width="70%"
    >
      <div v-if="currentQuestion" class="question-detail">
        <div class="detail-header">
          <div class="detail-meta">
            <el-tag 
              :type="getTypeTagType(currentQuestion.typeId)" 
              effect="plain"
              class="meta-tag"
            >
              {{ getQuestionTypeName(currentQuestion.typeId) }}
            </el-tag>
            <el-tag 
              :type="getDifficultyTagType(currentQuestion.difficulty)" 
              effect="light"
              class="meta-tag"
            >
              {{ getDifficultyText(currentQuestion.difficulty) }}
            </el-tag>
            <span class="meta-score">{{ currentQuestion.score }} 分</span>
          </div>
          <el-tag
            :type="getStatusTagType(currentQuestion.status)"
            effect="light"
          >
            {{ getStatusText(currentQuestion.status) }}
          </el-tag>
        </div>

        <div class="detail-content">
          <h3>题目内容</h3>
          <div class="content-text">{{ currentQuestion.content }}</div>
        </div>

        <!-- 选择题选项 -->
        <div v-if="isChoiceQuestion" class="detail-options">
          <h3>选项设置</h3>
          <ul class="options-list">
            <li 
              v-for="option in currentQuestion.options" 
              :key="option.id" 
              :class="{ 'correct-option': option.correct }"
            >
              <span class="option-letter">{{ option.optionOrder }}</span>
              <span class="option-content">{{ option.optionContent }}</span>
              <el-tag v-if="option.correct" type="success" size="small">正确答案</el-tag>
            </li>
          </ul>
        </div>

        <!-- 判断题答案 -->
        <div v-if="isJudgmentQuestion" class="detail-answer">
          <h3>正确答案</h3>
          <div class="answer-text">
            <el-tag type="success">{{ currentQuestion.correctAnswer ? '正确' : '错误' }}</el-tag>
          </div>
        </div>

        <!-- 填空题/简答题答案 -->
        <div v-if="isInputQuestion" class="detail-answer">
          <h3>参考答案</h3>
          <div class="answer-text">{{ currentQuestion.referAnswer }}</div>
        </div>

        <div class="detail-contest">
          <h3>所属竞赛</h3>
          <div class="contest-info">{{ currentQuestion.contestTitle }}</div>
        </div>

        <div v-if="currentQuestion.status === 0" class="detail-actions">
          <el-button type="success" @click="approveQuestion(currentQuestion.id)">通过审核</el-button>
          <el-button type="danger" @click="rejectQuestion(currentQuestion.id)">拒绝审核</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { 
  getQuestionList, 
  getQuestionDetail, 
  getQuestionTypes,
  reviewQuestion
} from '@/api/question'
import { getContestList } from '@/api/contest'

const loading = ref(false)
const questionList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const statusFilter = ref('')
const typeFilter = ref('')
const contestFilter = ref('')
const detailDialogVisible = ref(false)
const currentQuestion = ref(null)
const questionTypes = ref([])
const contestOptions = ref([])

// 状态选项
const statusOptions = [
  { value: '', label: '全部状态' },
  { value: '0', label: '待审核' },
  { value: '1', label: '已通过' },
  { value: '2', label: '已拒绝' }
]

// 获取题目列表
const fetchQuestionList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value,
      status: statusFilter.value,
      typeId: typeFilter.value,
      contestId: contestFilter.value
    }
    const res = await getQuestionList(params)
    questionList.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取题目列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取题目类型列表
const fetchQuestionTypes = async () => {
  try {
    const res = await getQuestionTypes()
    questionTypes.value = res.data
  } catch (error) {
    console.error('获取题目类型失败', error)
    ElMessage.error('获取题目类型失败')
  }
}

// 获取竞赛列表
const fetchContestOptions = async () => {
  try {
    const res = await getContestList({
      current: 1,
      size: 100
    })
    contestOptions.value = res.data.records
  } catch (error) {
    console.error('获取竞赛列表失败', error)
    ElMessage.error('获取竞赛列表失败')
  }
}

// 查看题目详情
const viewQuestion = async (id) => {
  try {
    const res = await getQuestionDetail(id)
    currentQuestion.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取题目详情失败')
    console.error(error)
  }
}

// 审核通过题目
const approveQuestion = (id) => {
  ElMessageBox.confirm(
    '确定要通过此题目的审核吗？',
    '审核确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(async () => {
    try {
      // 获取当前用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      if (!userInfo.id) {
        ElMessage.warning('无法获取审核人信息')
        return
      }
      
      // 调用审核API
      await reviewQuestion(id, 1, userInfo.id)
      ElMessage.success('题目已通过审核')
      fetchQuestionList()
      if (detailDialogVisible.value) {
        detailDialogVisible.value = false
      }
    } catch (error) {
      ElMessage.error('审核操作失败')
      console.error(error)
    }
  }).catch(() => {})
}

// 拒绝题目审核
const rejectQuestion = (id) => {
  ElMessageBox.confirm(
    '确定要拒绝此题目的审核吗？',
    '审核确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 获取当前用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      if (!userInfo.id) {
        ElMessage.warning('无法获取审核人信息')
        return
      }
      
      // 调用审核API
      await reviewQuestion(id, 2, userInfo.id)
      ElMessage.success('已拒绝题目审核')
      fetchQuestionList()
      if (detailDialogVisible.value) {
        detailDialogVisible.value = false
      }
    } catch (error) {
      ElMessage.error('审核操作失败')
      console.error(error)
    }
  }).catch(() => {})
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchQuestionList()
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
  fetchQuestionList()
}

// 页面大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchQuestionList()
}

// 页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchQuestionList()
}

// 格式化题目内容
const formatContent = (content) => {
  if (!content) return ''
  return content.length > 100 ? content.substring(0, 100) + '...' : content
}

// 格式化文本（通用）
const formatText = (text, length) => {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}

// 判断是否是选择题
const isChoiceQuestion = computed(() => {
  return currentQuestion.value && (currentQuestion.value.typeId === 1 || currentQuestion.value.typeId === 2)
})

// 判断是否是判断题
const isJudgmentQuestion = computed(() => {
  return currentQuestion.value && currentQuestion.value.typeId === 3
})

// 判断是否是填空题或简答题
const isInputQuestion = computed(() => {
  return currentQuestion.value && (currentQuestion.value.typeId === 4 || currentQuestion.value.typeId === 5)
})

// 获取题目类型名称
const getQuestionTypeName = (typeId) => {
  const type = questionTypes.value.find(t => t.id === typeId)
  return type ? type.typeName : '未知类型'
}

// 获取类型标签类型
const getTypeTagType = (typeId) => {
  const types = {
    1: 'primary',   // 单选题
    2: 'success',   // 多选题
    3: 'warning',   // 判断题
    4: 'danger',    // 填空题
    5: 'info'       // 简答题
  }
  return types[typeId] || 'info'
}

// 获取难度文本
const getDifficultyText = (difficulty) => {
  const texts = {
    1: '简单',
    2: '中等',
    3: '困难'
  }
  return texts[difficulty] || '未知'
}

// 获取难度标签类型
const getDifficultyTagType = (difficulty) => {
  const types = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return types[difficulty] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  }
  return texts[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return types[status] || 'info'
}

onMounted(() => {
  fetchQuestionTypes()
  fetchContestOptions()
  fetchQuestionList()
})
</script>

<style lang="scss" scoped>
.question-review-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
    
    .header-actions {
      display: flex;
      gap: 15px;
      
      .filter-container {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
        
        .filter-item {
          width: 200px;
        }
      }
    }
  }
  
  .list-card {
    margin-bottom: 20px;
    
    .question-content {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 300px;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .question-detail {
    .detail-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .detail-meta {
        display: flex;
        align-items: center;
        gap: 10px;
        
        .meta-tag {
          margin-right: 5px;
        }
        
        .meta-score {
          color: #e6a23c;
          font-weight: bold;
        }
      }
    }
    
    .detail-content {
      margin-bottom: 20px;
      
      h3 {
        margin-top: 0;
        margin-bottom: 10px;
        color: #303133;
        font-size: 16px;
      }
      
      .content-text {
        padding: 15px;
        background-color: #f8f9fa;
        border-radius: 8px;
        color: #303133;
        line-height: 1.6;
      }
    }
    
    .detail-options {
      margin-bottom: 20px;
      
      h3 {
        margin-top: 0;
        margin-bottom: 10px;
        color: #303133;
        font-size: 16px;
      }
      
      .options-list {
        list-style-type: none;
        padding: 0;
        margin: 0;
        
        li {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          padding: 10px;
          border-radius: 6px;
          background-color: #f8f9fa;
          
          &.correct-option {
            background-color: #f0f9eb;
            border-left: 3px solid #67c23a;
          }
          
          .option-letter {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 28px;
            height: 28px;
            border-radius: 50%;
            background-color: #e4e7ed;
            color: #606266;
            font-weight: bold;
            margin-right: 15px;
          }
          
          .option-content {
            flex: 1;
            margin-right: 10px;
          }
        }
      }
    }
    
    .detail-answer {
      margin-bottom: 20px;
      
      h3 {
        margin-top: 0;
        margin-bottom: 10px;
        color: #303133;
        font-size: 16px;
      }
      
      .answer-text {
        padding: 15px;
        background-color: #f0f9eb;
        border-radius: 8px;
        color: #303133;
        line-height: 1.6;
      }
    }
    
    .detail-contest {
      margin-bottom: 20px;
      
      h3 {
        margin-top: 0;
        margin-bottom: 10px;
        color: #303133;
        font-size: 16px;
      }
      
      .contest-info {
        padding: 15px;
        background-color: #f8f9fa;
        border-radius: 8px;
        color: #303133;
      }
    }
    
    .detail-actions {
      display: flex;
      justify-content: center;
      gap: 20px;
      margin-top: 30px;
    }
  }
}
</style> 